﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Marbles.Core.Handlers
{
    public class AuthenticationProvider : HttpHandlerBase, IHttpHandlerBase
    {
        public string Verbs
        {
            get { return "POST"; }
        }

        public bool Validate
        {
            get { return false; }
        }

        public string Path
        {
            get { return "Authenticate.axd"; }
        }

        public string Name
        {
            get { return this.GetType().Name; }
        }

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(System.Web.HttpContext context)
        {
            string type = "logout";
            string username = string.Empty;
            string password = string.Empty;

            if (context.Request.Form["loginType"] != null) { type = context.Request.Form["loginType"].ToString(); }
            if (context.Request.Form["loginUsername"] != null) { username = context.Request.Form["loginUsername"].ToString(); }
            if (context.Request.Form["loginPassword"] != null) { password = context.Request.Form["loginPassword"].ToString(); }

            Marbles.Core.Authentication.AuthenticationProvider auth = Marbles.Core.Authentication.AuthenticationProvider.CreateProviderInstance();

            context.Response.ContentType = "text/plain";

            switch (type.ToLower())
            {
                case "login":
                case "sitelogin":
                    bool success = false;
                    if (auth.Provider == "OpenId")
                    {
                        success = auth.Login(username, "");
                    }
                    else
                    {
                        success = auth.Login(username, password);
                    }

                    context.Response.Write(success.ToString().ToLower());
                    break;
                case "logout":
                    context.Response.Write(auth.Logout().ToString().ToLower());
                    break;
            }
        }
    }
}